package com.example.latch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author chentao
 * @version 1.0
 * @description: TODO
 * @date 2025/3/23 下午7:34
 */
public class MySqlLatchUtils {

    static Logger logger = LoggerFactory.getLogger(MySqlLatchUtils.class);

    public static void latchInAction(DataSource dataSource, MysqlLatchListener mysqlLatchListener) {
        CompletableFuture.supplyAsync(new Supplier<MySqlSyncLatch>() {
            @Override
            public MySqlSyncLatch get() {
                MySqlSyncLatch mySqlSyncLatch = null;
                try {
                    mySqlSyncLatch = new MySqlSyncLatch(dataSource, mysqlLatchListener);
                    mySqlSyncLatch.start();
                } catch (Exception e) {
                    logger.warn("mySqlSyncLatch start error: " + e.getMessage());
                }
                return mySqlSyncLatch;
            }
        }).thenAcceptAsync(new Consumer<MySqlSyncLatch>() {
            @Override
            public void accept(MySqlSyncLatch mySqlSyncLatch) {
                if (mySqlSyncLatch != null) {
                    mySqlSyncLatch.stop();
                }
            }
        }).whenComplete(new BiConsumer<Void, Throwable>() {
            @Override
            public void accept(Void unused, Throwable throwable) {
                logger.warn("mySqlSyncLatch stop ...");
            }
        });
    }

    public static void latchInAction(DataSource dataSource, String sql, MysqlLatchListener mysqlLatchListener) {
        CompletableFuture.supplyAsync(new Supplier<MySqlSyncLatch>() {
            @Override
            public MySqlSyncLatch get() {
                MySqlSyncLatch mySqlSyncLatch = null;
                try {
                    mySqlSyncLatch = new MySqlSyncLatch(dataSource, sql, mysqlLatchListener);
                    mySqlSyncLatch.start();
                } catch (Exception e) {
                    logger.warn("mySqlSyncLatch start error: " + e.getMessage());
                }
                return mySqlSyncLatch;
            }
        }).thenAcceptAsync(new Consumer<MySqlSyncLatch>() {
            @Override
            public void accept(MySqlSyncLatch mySqlSyncLatch) {
                if (mySqlSyncLatch != null) {
                    mySqlSyncLatch.stop();
                }
            }
        }).whenComplete(new BiConsumer<Void, Throwable>() {
            @Override
            public void accept(Void unused, Throwable throwable) {
                logger.warn("mySqlSyncLatch stop ...");
            }
        });
    }
}
